package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.AddFolderPermissionRequest;
import com.docmgmt.mvp.dto.FolderPermissionVO;
import com.docmgmt.mvp.dto.Result;
import com.docmgmt.mvp.dto.UpdateFolderPermissionRequest;
import com.docmgmt.mvp.exception.UnauthorizedException;
import com.docmgmt.mvp.service.FolderPermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * <p>
 * 文件夹权限管理 API（v3.0 RBAC）
 * </p>
 *
 * @author Dora
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/folders")
@RequiredArgsConstructor
public class FolderPermissionController {

    private final FolderPermissionService folderPermissionService;

    /**
     * 5.1.1 查询文件夹权限列表
     *
     * GET /api/v1/folders/{folderId}/permissions
     */
    @GetMapping("/{folderId}/permissions")
    public Result<List<FolderPermissionVO>> listPermissions(@PathVariable Long folderId) {
        Long userId = getCurrentUserId();

        log.info("GET /api/v1/folders/{}/permissions - userId={}", folderId, userId);

        List<FolderPermissionVO> permissions = folderPermissionService.listFolderPermissions(folderId, userId);

        return Result.success("查询成功", permissions);
    }

    /**
     * 5.1.2 添加文件夹权限
     *
     * POST /api/v1/folders/{folderId}/permissions
     */
    @PostMapping("/{folderId}/permissions")
    public Result<FolderPermissionVO> addPermission(
            @PathVariable Long folderId,
            @Valid @RequestBody AddFolderPermissionRequest request) {

        Long userId = getCurrentUserId();

        log.info("POST /api/v1/folders/{}/permissions - userId={}, request={}",
                folderId, userId, request);

        FolderPermissionVO permission = folderPermissionService.addFolderPermission(folderId, request, userId);

        return Result.success("权限添加成功", permission);
    }

    /**
     * 5.1.3 修改文件夹权限
     *
     * PUT /api/v1/folders/{folderId}/permissions/{permissionId}
     */
    @PutMapping("/{folderId}/permissions/{permissionId}")
    public Result<FolderPermissionVO> updatePermission(
            @PathVariable Long folderId,
            @PathVariable Long permissionId,
            @Valid @RequestBody UpdateFolderPermissionRequest request) {

        Long userId = getCurrentUserId();

        log.info("PUT /api/v1/folders/{}/permissions/{} - userId={}, request={}",
                folderId, permissionId, userId, request);

        FolderPermissionVO permission = folderPermissionService.updateFolderPermission(
                folderId, permissionId, request, userId);

        return Result.success("权限修改成功", permission);
    }

    /**
     * 5.1.4 删除文件夹权限
     *
     * DELETE /api/v1/folders/{folderId}/permissions/{permissionId}
     */
    @DeleteMapping("/{folderId}/permissions/{permissionId}")
    public Result<Void> deletePermission(
            @PathVariable Long folderId,
            @PathVariable Long permissionId) {

        Long userId = getCurrentUserId();

        log.info("DELETE /api/v1/folders/{}/permissions/{} - userId={}",
                folderId, permissionId, userId);

        folderPermissionService.deleteFolderPermission(folderId, permissionId, userId);

        return Result.success("权限删除成功");
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new UnauthorizedException("未登录");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof Long) {
            return (Long) principal;
        } else if (principal instanceof String) {
            try {
                return Long.parseLong((String) principal);
            } catch (NumberFormatException e) {
                throw new UnauthorizedException("无效的用户ID");
            }
        }

        throw new UnauthorizedException("无法获取用户ID");
    }
}
